import {useMemo} from 'react';
import DateUtil from "@/utils/DateUtils";

export type LessonStatus = 'normal' | 'overdue' | 'forbid' | 'full' | 'start';

export type StatusConfigItem = {
  text: string;
  color: string;
  bgColor: string;
  tagType: 'success' | 'warning' | 'danger' | 'default' | 'primary';
};

export type LessonStatusConfig = {
  [key in LessonStatus]: StatusConfigItem;
};

const LESSON_STATUS_CONFIG: LessonStatusConfig = {
  normal: {
    text: '可预约',
    color: '#07c160',
    bgColor: '#f2fbf6',
    tagType: 'success'
  },
  full: {
    text: '已满员',
    color: '#ff4d4f',
    bgColor: '#fff2f0',
    tagType: 'danger'
  },
  forbid: {
    text: '禁止预约',
    color: '#faad14',
    bgColor: '#fffbe6',
    tagType: 'warning'
  },
  start: {
    text: '进行中',
    color: '#1890ff',
    bgColor: '#e6f7ff',
    tagType: 'primary'
  },
  overdue: {
    text: '已结束',
    color: '#8c8c8c',
    bgColor: '#f5f5f5',
    tagType: 'default'
  }
};

export function useLesson(lesson: API.ILesson) {
  /**
   * 计算课程状态（优先级从高到低）
   */
  const status = useMemo<LessonStatus>(() => {
    const now = new Date();

    // 1. 检查是否已过期
    if (DateUtil.isBefore(lesson.endTime, now)) {
      return 'overdue';
    }

    // 2. 检查是否已开始
    if (
      DateUtil.isBefore(lesson.startTime, now) &&
      now < new Date(lesson.endTime) &&
      lesson.status === '1' &&
      lesson.currentStudents < lesson.maxStudents
    ) {
      return 'start';
    }

    // 3. 检查是否禁止预约
    if (lesson.status === '3') {
      return 'forbid';
    }

    // 4. 检查是否已满员
    if (lesson.status === '2' || lesson.currentStudents >= lesson.maxStudents) {
      return 'full';
    }

    // 5. 默认正常状态
    return 'normal';
  }, [lesson]);

  /**
   *  剩余名额
   */
  const remainingSeats = useMemo(() => {
    return Math.max(0, lesson.maxStudents - lesson.currentStudents);
  }, [lesson]);

  /**
   * 计算课程时长（小时）
   */
  const duration = useMemo(() => {
    if (!lesson.startTime || !lesson.endTime) return 0;
    const start = new Date(lesson.startTime);
    const end = new Date(lesson.endTime);
    return Number(((end.getTime() - start.getTime()) / (1000 * 60 * 60)).toFixed(1));
  }, [lesson]);

  /**
   * 是否可预约
   */
  const canReserve = useMemo(() => status === 'normal', [status]);

  /**
   * 是否可取消预约
   */
  const canCancel = useMemo(() => {
    return !['overdue', 'forbid', 'start'].includes(status);
  }, [status]);

  /**
   * 当前状态配置
   */
  const currentStatusConfig = useMemo(() => LESSON_STATUS_CONFIG[status], [status]);


  return {
    status,
    remainingSeats,
    duration,
    canReserve,
    canCancel,
    currentStatusConfig,

    // 状态判断快捷方式
    isOverdue: status === 'overdue',
    isForbid: status === 'forbid',
    isFull: status === 'full',
    isNormal: status === 'normal',
    isStarted: status === 'start',

    // 状态文本映射
    statusText: LESSON_STATUS_CONFIG[status].text,
    lessonTitle: `${lesson.licenseTypeName}(${lesson.licenseTypeCode})`,
  };
}
